local frame_table = {}
local srtp = Proto("srtp", "Secure Real-time Transport Protocol");

srtp.prefs.key1 = Pref.string( "key1(base64)", "", "master key 1")
srtp.prefs.key2 = Pref.string( "key2(base64)", "", "master key 2")

srtp.fields = {}

local path = "libsrtp_lua.dll"
local module_init = package.loadlib(path,"module_init")
local set_key = package.loadlib(path,"set_key")
local decrypt = package.loadlib(path,"decrypt")

local rtp_encap = Dissector.get("rtp")

function srtp.init()
	print("srtp.init")
	module_init()
	local key1 = ByteArray.new(srtp.prefs.key1, true):base64_decode():raw()
	local key2 = ByteArray.new(srtp.prefs.key2, true):base64_decode():raw()
	set_key(key1, key2)
end

function srtp.prefs_changed()
	print("srtp.prefs_changed")
	local key1 = ByteArray.new(srtp.prefs.key1, true):base64_decode():raw()
	local key2 = ByteArray.new(srtp.prefs.key2, true):base64_decode():raw()
	set_key(key1, key2)
end

function srtp.dissector(buf, pkt, tree)
	local rtp_buf= nil
	if pkt.visited == false then 
		rtp_buf = decrypt(buf:raw())
		if rtp_buf ~= nil then 
			frame_table[pkt.number] = rtp_buf
		end
	else
		rtp_buf = frame_table[pkt.number]
	end
	
	if rtp_buf ~= nil then
		pkt.cols.protocol = srtp.name
		local b = ByteArray.new(rtp_buf, true)
		local tvb = ByteArray.tvb(b, "decrypted RTP")
		tree:add(buf(), "Secure Real-time Transport Protocol")
		rtp_encap:call(tvb, pkt, tree)
	else
		rtp_encap:call(buf, pkt, tree)
	end
end

local udp_encap_table = DissectorTable.get("udp.port")
udp_encap_table:add(9000, srtp)